package dmas.lab.schedulers;

import java.util.ArrayList;
import java.util.List;

import dmas.lab.tasks.ReceiveMessageEvent;
import dmas.lab.tasks.SendSpamEvent;

public class Scheduler implements TaskCaller {

	private List<Event> receiveEvents;
	private List<Event> sendEvents;

	// event currently executing
	private Event currentEvent = null;

	public Scheduler() {
		receiveEvents = new ArrayList<Event>();
		sendEvents = new ArrayList<Event>();
	}

	public void addEvent(Event event) {
		if (event instanceof SendSpamEvent) {
			handleEvent(sendEvents, event);
		} else if (event instanceof ReceiveMessageEvent) {
			handleEvent(receiveEvents, event);
		}
		if (currentEvent == null) {
			startNewTask();
		}
	}

	private void handleEvent(final List<Event> list, final Event event) {
		try {
			System.out.println("Waiting");
			Thread.sleep(1000);
		} catch (Exception e) {
		}
		list.add(event);
	}

	private boolean deleteEvent(List<Event> list, Event event) {
//		System.out.println("Deleting event: " + event.getEventID());
		return list.remove(event);
	}

	/***
	 * Handles information returned by Event
	 * */
	@Override
	public void callback(Event callbackEvent) {
		currentEvent = null;
		if (callbackEvent instanceof SendSpamEvent) {
			deleteEvent(sendEvents, callbackEvent);
		} else if (callbackEvent instanceof ReceiveMessageEvent) {
			deleteEvent(receiveEvents, callbackEvent);
		}
		startNewTask();
	}

	private void startNewTask() {
		if (!receiveEvents.isEmpty()) {
			currentEvent = receiveEvents.get(0);
		} else if (!sendEvents.isEmpty()) {
			currentEvent = sendEvents.get(0);
		}
		if(currentEvent != null){
			currentEvent.run();
		}
	}

	@Override
	public void handleException(Exception e) {
		System.out.println(e.getMessage());
	}
}
